package com.example;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HtmlUtil;
import com.example.utils.RandomUtil;
import com.mybatisflex.core.MybatisFlexBootstrap;
import com.mybatisflex.core.datasource.DataSourceKey;
import com.mybatisflex.core.row.Db;
import com.mybatisflex.core.row.DbChain;
import com.mybatisflex.core.row.Row;
import com.zaxxer.hikari.HikariDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.yaml.snakeyaml.Yaml;

import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

public class PortalMigrate {

    // 统一日志
    private static final Logger logger = LoggerFactory.getLogger(Application.class);
    public static void main(String[] args) {

        logger.warn("args:" + Arrays.toString(args));

        if (args.length == 0) {
            logger.error("请输入参数");
            return;
        }

        if ("article".equals(args[0])) {
            migrateArticle();
        } else if ("category".equals(args[0])) {
            migrateCategory();
        } else {
            logger.error("请输入正确的参数");
        }

    }

    // 迁移文章
    public static void migrateArticle() {


        // 加载YML配置文件
        Yaml yaml = new Yaml();
        InputStream inputStream = Application.class.getResourceAsStream("/application.yml");
        Map<String, Object> config = yaml.load(inputStream);

        // 设置数据源
        HikariDataSource dsPortalOld = new HikariDataSource();
        Map<String, Object> ds1Config = (Map<String, Object>) config.get("dsPortalOld");
        dsPortalOld.setJdbcUrl((String) ds1Config.get("url"));
        dsPortalOld.setUsername((String) ds1Config.get("username"));
        dsPortalOld.setPassword((String) ds1Config.get("password"));

        HikariDataSource dsPortalNew = new HikariDataSource();
        Map<String, Object> ds2Config = (Map<String, Object>) config.get("dsPortalNew");
        dsPortalNew.setJdbcUrl((String) ds2Config.get("url"));
        dsPortalNew.setUsername((String) ds2Config.get("username"));
        dsPortalNew.setPassword((String) ds2Config.get("password"));

        MybatisFlexBootstrap.getInstance()
                .setDataSource("ds1", dsPortalOld)
                .addDataSource("ds2", dsPortalNew)
                .start();
        // 查（关联查）
        var sql = """
                SELECT
                	news.id,
                	news.catid, -- catid将要匹配到新库的category.ext05 --> category.id/code 从而得到新archive.category_id
                	news.title, 
                	news.thumb,
                	news.keywords,
                	news.description,
                	news.author,
                	news.`status`,
                	news.url,
                	news.inputtime,
                	`data`.content,
                	news.updatetime 
                FROM
                	ptl_1_news AS news
                	INNER JOIN
                	ptl_1_news_data_0 AS `data`
                	ON
                		news.id = `data`.id
                	ORDER BY inputtime DESC
                """;
        List<Row> list = Db.selectListBySql(sql);
        //logger.info(list.toString());
        list.forEach(oldArt -> {
            logger.info(oldArt.toString());
            // 构造数据
            String aid = IdUtil.getSnowflakeNextIdStr();
            // 把inputtime和updatetime都从时间戳整数转为字符串
            String create_time = DateUtil.format(DateUtil.date((Long) oldArt.get("inputtime")*1000), "yyyy-MM-dd HH:mm:ss");
            String update_time = DateUtil.format(DateUtil.date((Long) oldArt.get("updatetime")*1000), "yyyy-MM-dd HH:mm:ss");
            // 切换数据源（上文默认数据源为ds1)
            try{
                DataSourceKey.use("ds2");
            } catch (Exception e) {
                e.printStackTrace();
            }
            // 插入 // 先在archive插入，得到id，然后在article中创建，articlie.aid-->archive.id
            DbChain.table("system_archives")
                    .set("id", aid)
                    .set("title", oldArt.get("title"))
                    .set("properties", "n")
                    .set("image_path", "")
                    .set("tag", "")
                    .set("category_id", "242c2c03b22c48579b3c17d6e0fd5eae")
                    .set("category_ids", ".he9g4d0j.v35683wr")
                    .set("create_by", "9f4b807db2e94670bb02cdc212ea7389")
                    .set("create_time", create_time)
                    .set("update_time", update_time)
                    .save();
            String id = IdUtil.getSnowflakeNextIdStr();
            // content要转义恢复为为html标签
            String content = HtmlUtil.unescape(oldArt.get("content").toString());
            DbChain.table("system_article")
                    .set("id", id)
                    .set("aid", aid)
                    .set("ext04", oldArt.get("id"))
                    .set("ext05", oldArt.get("url"))
                    .set("create_by", "9f4b807db2e94670bb02cdc212ea7389")
                    .set("create_time", create_time)
                    .set("update_time", update_time)
                    .set("content", content)
                    .save();

        });



    }

    // 迁移栏目
    public static void migrateCategory() {


        // 加载YML配置文件
        Yaml yaml = new Yaml();
        InputStream inputStream = Application.class.getResourceAsStream("/application.yml");
        Map<String, Object> config = yaml.load(inputStream);

        // 设置数据源
        HikariDataSource dsPortalOld = new HikariDataSource();
        Map<String, Object> ds1Config = (Map<String, Object>) config.get("dsPortalOld");
        dsPortalOld.setJdbcUrl((String) ds1Config.get("url"));
        dsPortalOld.setUsername((String) ds1Config.get("username"));
        dsPortalOld.setPassword((String) ds1Config.get("password"));

        HikariDataSource dsPortalNew = new HikariDataSource();
        Map<String, Object> ds2Config = (Map<String, Object>) config.get("dsPortalNew");
        dsPortalNew.setJdbcUrl((String) ds2Config.get("url"));
        dsPortalNew.setUsername((String) ds2Config.get("username"));
        dsPortalNew.setPassword((String) ds2Config.get("password"));

        MybatisFlexBootstrap.getInstance()
                .setDataSource("ds1", dsPortalOld)
                .addDataSource("ds2", dsPortalNew)
                .start();
        // 查
        DbChain.table("ptl_1_share_category")
        .select("id, tid, pid, mid, pids, name, dirname, pdirname, child, `show`, banner")
        .where("`show` = ?",1)
        .list()
        .forEach(oldCat -> {
            //
            logger.info(oldCat.toString());
            // 构造数据
            String id = IdUtil.getSnowflakeNextIdStr();
            String parent_id = "-1"; // TODO 这里手工做数据处理，在后台再修改
            String code = RandomUtil.getCharAndNum(8);
            String create_time = DateUtil.now();
            String targetTable = "system_category";
            // 切换数据源（上文默认数据源为ds1)
            try{
                DataSourceKey.use("ds2");
            } catch (Exception e) {
                e.printStackTrace();
            }
            // 查新库看是否有
            if (DbChain.table(targetTable).where("ext05 = ?", oldCat.get("id")).count() > 0) {
                logger.info("栏目已存在");
                return;
            }
            // 插入
            DbChain.table(targetTable)
                    .set("id", id)
                    .set("cnname", oldCat.get("name"))
                    .set("code", code)
                    .set("form_id", "c17ddcad9fb149a6bf90f7bba0e0696b")
                    .set("cat_model", 1)
                    .set("cover_temp", "/index_article.html")
                    .set("list_temp", "/list_article.html")
                    .set("article_temp", "/article_article.html")
                    .set("default_editor", "ue")
                    .set("is_show", "1")
                    .set("level", "1")
                    .set("create_by", "9f4b807db2e94670bb02cdc212ea7389")
                    .set("create_time", create_time)
                    .set("parent_id", parent_id)
                    .set("ext05", oldCat.get("id"))
            .save();
        });



    }


}
